package jsu.yym.tiktok.service;

import jsu.yym.tiktok.pojo.*;
import jsu.yym.tiktok.mapper.FileMapper;
import jsu.yym.tiktok.server.JwtUtil;
import jsu.yym.tiktok.server.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Objects;

@Service
public class LoginServiceImp implements LoginService{
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private FileMapper fileMapper;


    @Override
    public ResponseResult login(User user) {
        System.out.println(user.toString());
        redisCache.setCacheObject("pwd:"+user.getUsername(),user.getPassword());
        //进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken= new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());

        System.out.println("jjjj");

        Authentication authentication = authenticationManager.authenticate(authenticationToken);

        System.out.println(authentication.toString()+"hhhh");
        if(Objects.isNull(authentication)){
            throw new RuntimeException("登录失败");
        }

        //认证通过,使用userid生成一个jwt，jwt存入ResponseResult返回
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userId = loginUser.getUsername().toString();

        //返回给前端的jwt
        String jwt = JwtUtil.createJWT(userId);
        System.out.println(jwt+"   "+userId);
        System.out.println("login:"+loginUser.toString());

        //存到redis
        redisCache.setCacheObject("login:"+userId,loginUser);
        HashMap<String,Object> token = new HashMap<>();
        token.put("token",jwt);
//        LoginReturn loginReturn = new LoginReturn();
//        loginReturn.setAccount(userId);
//        loginReturn.setToken(token);
        return new ResponseResult(200,"登录成功",token);

    }

    @Override
    public ResponseResult loginOut() {
        return null;
    }
}
